<template>
    <div class="app-container">
      <div class="filter-container">
        <div class="lineBox">
          <el-form :inline="true" :model="listQuery" class="demo-form-inline">
            <el-form-item label="任务名称">
              <el-input
                v-model="listQuery.name"
                placeholder="请输入任务名称"
                style="width: 200px;"
                size="mini"
                clearable
                @keyup.enter.native="handleFilter"
                @clear="handleFilter"
              />
            </el-form-item>
            <el-form-item label="全宗号">
              <el-input
                v-model="listQuery.qzh"
                placeholder="请输入全宗号"
                style="width: 200px;"
                size="mini"
                clearable
                @keyup.enter.native="handleFilter"
                @clear="handleFilter"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="listQuery.status"
                placeholder="请选择状态"
                style="width: 140px"
                size="mini"
                clearable
                @change="handleFilter"
              >
                <el-option label="处理中" :value="0" />
                <el-option label="已完成" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button size="mini" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
              </el-button>
              <el-button size="mini" icon="el-icon-refresh" @click="handleReset">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
  
      <div class="document-table" style="min-height: 600px; margin-top: 20px;">
        <div style="margin-bottom: 10px;">
          <el-button v-if="isAdmin"
            size="mini" 
            type="danger" 
            :disabled="selectedIds.length === 0" 
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
  
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          fit
          size="mini"
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" prop="id" align="center" width="50" />
          <el-table-column label="任务名称" prop="name" align="center" min-width="150" show-overflow-tooltip />
          <el-table-column label="全宗号" prop="qzh" align="center" min-width="50" show-overflow-tooltip />
          <el-table-column label="进度" align="center" width="120">
            <template slot-scope="{row}">
              <div style="position: relative;">
                <el-progress 
                  :percentage="row.progress || 0" 
                  :status="row.progress >= 100 ? 'success' : ''"
                  :stroke-width="15"
                  :show-text="false">
                </el-progress>
                <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: flex; align-items: center; justify-content: center;">
                  <span style="font-size: 14px;">{{ row.progress || 0 }}%</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="80">
            <template slot-scope="{row}">
              <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
                {{ row.status === 1 ? '已完成' : '处理中' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" min-width="150">
            <template slot-scope="{row}">
              <span>{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="更新时间" align="center" min-width="150">
            <template slot-scope="{row}">
              <span>{{ row.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" align="center" min-width="280" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button size="mini" type="primary" @click="handleViewQueue(row)">
                查看队列
              </el-button>
              <el-button size="mini" type="success" @click="handleExportDbf(row)">
                处理结果路径
              </el-button>
              <el-button size="mini" type="info" @click="handleRetryFailed(row)">
                重新处理异常记录
              </el-button>
              <el-button v-if="isAdmin" size="mini" type="danger" @click="handleDelete(row,$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          size="mini"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="getList"
        />
      </div>
  

    </div>
  </template>
  
  <script>

  import { articletaskApi } from '@/api/articletask'
  import Pagination from '@/components/Pagination'
  import { parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  
  export default {
    computed: {
      ...mapGetters([
        'roles',
        'name'
      ]),
      // 判断当前用户是否为管理员
      isAdmin() {
        return this.roles.includes('admin')
      }
    },
    name: 'ProcessDocumentFile',
    components: { Pagination },
    filters: {
      parseTime
    },
    data() {
      return {
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: false,
        selectedIds: [],
        logDialogVisible: false,
        currentLog: '',
        listQuery: {
          page: 1,
          limit: 10,
          folder: undefined,
          qzh: undefined,
          status: undefined,
          is_delete: '0' // 默认查询未删除的记录
        }
      }
    },
    created() {
      this.getList()
    },
    mounted() {
      // 3秒后检查是否有数据，如果没有就显示提示
      setTimeout(() => {
        if (this.list.length === 0 && !this.listLoading) {
          this.$message.warning('暂无数据，或者后端API尚未完全配置')
        }
      }, 3000)
    },
    methods: {

      async handleRetryFailed(row) {
        try {
          this.$message({
            message: '正在重新处理失败项...',
            type: 'info',
            duration: 2000
          });
          
          // 调用后端API
          const response = await articletaskApi('retryFailedItems', { id: row.id });
          
          if (response.code === 200) {
            this.$message({
              message: response.message || '重新处理请求已发送，请稍后刷新查看结果',
              type: 'success',
              duration: 2000
            });
            
            // 延迟刷新列表，以便看到最新状态
            setTimeout(() => {
              this.getList();
            }, 1500);
          } else {
            this.$message.error(response.message || '重新处理失败项失败');
          }
        } catch (error) {
          console.error('重新处理失败项出错:', error);
          this.$message.error('重新处理失败项失败，请稍后重试');
        }
      },
      async getList() {
        this.listLoading = true
        try {
          // 添加调试信息
          console.log('发送请求参数:', this.listQuery)
          
          let response
          try {
            response = await articletaskApi('getTaskList', this.listQuery)
          } catch (apiError) {
            console.error('API调用失败:', apiError)
            // 使用模拟数据
            response = mockProcessDocumentData()
          }
          
          console.log('返回数据:', response)
          
          if (response.code == 200) {
            // 处理后端返回的实际数据结构
            if (response.data && response.data.items) {
              // 新的数据结构 {total: x, items: [...], page: x, limit: x}
              this.list = response.data.items
              this.total = response.data.total || 0
              
              // 如果后端返回了页码和分页大小，同步到前端
              if (response.data.page) {
                this.listQuery.page = response.data.page
              }
              if (response.data.limit) {
                this.listQuery.limit = response.data.limit
              }
            } else if (response.data && response.data.resultList) {
              // 旧的数据结构处理方式
              this.list = response.data.resultList
              this.total = response.data.totalCount || response.totalCount || 0
            } else if (Array.isArray(response.data)) {
              // 直接返回数组的情况
              this.list = response.data
              this.total = response.totalCount || response.data.length || 0
            } else {
              // 数据结构不符合预期
              console.warn('后端返回的数据结构不符合预期:', response.data)
              this.list = []
              this.total = 0
              
              // 如果没有返回有效数据，可以考虑使用测试数据

            }
            
            setTimeout(() => {
              this.listLoading = false
            }, 300)
          } else {
            this.$message.error(response.message || '获取列表失败')
            this.listLoading = false
            // API调用返回错误，使用测试数据
      
          }
        } catch (error) {
          console.error('获取列表失败:', error)
          this.$message.error('获取列表失败，显示测试数据')
          this.listLoading = false
          // API调用异常，使用测试数据
       
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleReset() {
        this.listQuery = {
          page: 1,
          limit: 10,
          folder: undefined,
          qzh: undefined,
          status: undefined,
          is_delete: '0' // 保持未删除的查询条件
        }
        this.getList()
      },
      handleSelectionChange(val) {
        this.selectedIds = val.map(item => item.id)
      },
      
      async handleViewLog(row) {
        if (row.logs) {
          this.currentLog = row.logs
          this.logDialogVisible = true
        } else {
          try {
            // 显示加载中提示
            this.currentLog = '正在加载日志...'
            this.logDialogVisible = true
  
            const response = await articletaskApi('getDocumentLog', { id: row.id })
            if (response.code == 200) {
              // 根据实际返回结构提取日志内容
              if (response.data && response.data.logs) {
                this.currentLog = response.data.logs
              } else if (response.data) {
                // 如果直接返回日志内容
                this.currentLog = typeof response.data === 'string' ? response.data : JSON.stringify(response.data, null, 2)
              } else {
                this.currentLog = '暂无日志数据'
              }
            } else {
              this.currentLog = '获取日志失败: ' + (response.message || '未知错误')
            }
          } catch (error) {
            console.error('获取日志失败:', error)
            this.currentLog = '获取日志失败: ' + (error.message || '未知错误')
          }
        }
      },
      
      // 打开队列查看页面
      handleViewQueue(row) {

        console.log(row)
       
        window.open(`/ocrbatch/artqueue?taskid=${row.id}`, '_blank')
      },
      
      async handleBatchDelete() {
        if (this.selectedIds.length === 0) {
          this.$message.warning('请选择要删除的记录')
          return
        }
  
        this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const data = { ids: this.selectedIds.join(',') } // 按照后端API需要的格式，用逗号连接ID
            const response = await articletaskApi('batchDeletetasklist', data)
            if (response.code == 200) {
              this.$notify({
                title: '成功',
                message: response.message || '批量删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: response.message || '批量删除失败',
                type: 'error',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('批量删除失败:', error)
            this.$message.error('批量删除失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      async handleDelete(row, index) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const data = { id: row.id }
            const response = await articletaskApi('deletetasklist', data)
            if (response.code == 200) {
              this.$notify({
                title: '成功',
                message: response.message || '删除成功',
                type: 'success',
                duration: 2000
              })
              this.list.splice(index, 1)
              // 如果是最后一条记录被删除，且不是第一页，则跳转到上一页
              if (this.list.length === 0 && this.listQuery.page > 1) {
                this.listQuery.page -= 1;
                this.getList();
              }
            } else {
              this.$notify({
                title: '失败',
                message: response.message || '删除失败',
                type: 'error',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      handleExportDbf(row) {
        if (row.pathName) {
          const h = this.$createElement;
          // 显示路径并提供复制功能
          this.$alert(
            `<div class="path-dialog-content">
              <div class="path-title">处理结果路径：</div>
              <div class="path-container">
                <code id="resultPath">${row.pathName}</code>
              </div>
              <div class="path-tips">
                <i class="el-icon-info"></i> 点击下方按钮可复制完整路径
              </div>
            </div>`,
            '处理结果路径',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '复制路径',
              cancelButtonText: '关闭',
              showCancelButton: true,
              customClass: 'path-dialog',
              beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                  navigator.clipboard.writeText(row.pathName).then(() => {
                    this.$message({
                      type: 'success',
                      message: '路径已复制到剪贴板',
                      duration: 1500
                    });
                    // 添加一个短暂延迟后关闭对话框，让用户看到复制成功的提示
                    setTimeout(() => {
                      done();
                    }, 300);
                  }).catch(err => {
                    console.error('复制失败:', err);
                    this.$message.error('复制失败，请手动复制');
                    done();
                  });
                } else {
                  done();
                }
              }
            }
          );

          // 手动添加图标到确认按钮
          setTimeout(() => {
            const confirmBtn = document.querySelector('.path-dialog .el-button--primary');
            if (confirmBtn) {
              const icon = document.createElement('i');
              icon.className = 'el-icon-document-copy';
              icon.style.marginRight = '5px';
              confirmBtn.insertBefore(icon, confirmBtn.firstChild);
            }
          }, 100);
        } else {
          this.$message.warning('该任务没有处理结果路径');
        }
      },
      
      // 文件下载辅助方法
      downloadFile(data, fileName) {
        // 处理不同类型的数据
        let blob;
        if (typeof data === 'string' && data.startsWith('data:')) {
          // 处理base64数据
          const parts = data.split(',');
          const contentType = parts[0].split(':')[1].split(';')[0];
          const raw = window.atob(parts[1]);
          const rawLength = raw.length;
          const uInt8Array = new Uint8Array(rawLength);
          
          for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
          }
          
          blob = new Blob([uInt8Array], { type: contentType });
        } else if (data instanceof Blob) {
          // 已经是Blob对象
          blob = data;
        } else {
          // 其他类型的数据
          blob = new Blob([data], { type: 'application/octet-stream' });
        }
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      },

   
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .document-table {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  }
  
  .log-container {
    max-height: 400px;
    overflow-y: auto;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    
    pre {
      white-space: pre-wrap;
      word-wrap: break-word;
      margin: 0;
      font-family: "Courier New", monospace;
      font-size: 13px;
      line-height: 1.5;
    }
  }
  
  .empty-log {
    text-align: center;
    color: #909399;
    padding: 20px 0;
  }
  </style>
  
  <style>
  /* 全局样式，用于自定义弹窗 */
  .path-dialog .el-message-box__content {
    padding: 20px !important;
  }
  
  .path-dialog .el-message-box__header {
    padding: 15px 20px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .path-dialog .el-message-box__title {
    font-size: 16px;
    color: #303133;
    font-weight: 500;
  }
  
  .path-dialog-content {
    margin: 10px 0;
  }
  
  .path-dialog-content .path-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 10px;
    font-weight: 500;
  }
  
  .path-dialog-content .path-container {
    background-color: #f5f7fa;
    border-radius: 4px;
    padding: 12px;
    margin: 10px 0;
    border: 1px solid #e4e7ed;
    position: relative;
  }
  
  .path-dialog-content .path-container code {
    display: block;
    word-break: break-all;
    font-family: Monaco, Consolas, Courier, monospace;
    font-size: 13px;
    color: #409eff;
    line-height: 1.6;
    user-select: all;
  }
  
  .path-dialog-content .path-tips {
    font-size: 12px;
    color: #909399;
    margin-top: 10px;
    display: flex;
    align-items: center;
  }
  
  .path-dialog-content .path-tips i {
    margin-right: 5px;
    font-size: 14px;
  }
  
  .path-dialog .el-message-box__btns {
    padding: 10px 20px 20px;
    border-top: 1px solid #e4e7ed;
  }
  
  .path-dialog .el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
    padding: 10px 20px;
    font-size: 14px;
    transition: all 0.3s;
  }
  
  .path-dialog .el-button--primary:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
    transform: translateY(-1px);
  }
  
  .path-dialog .el-button--primary i {
    margin-right: 5px;
  }
  </style>